/**
 * GeoSOA/olap4js/Util.js
 *
 * Util namespace
 *
 * Copyright (C) 2009 GeoSOA Research Group, Universite Laval
 * See LICENSE file under this distribution for licensing information
 * 
 * @author Etienne Dube
 * @since 20090618
 **/

dojo.provide("GeoSOA.olap4js.Util");

dojo.require("GeoSOA.olap4js.AxisMeta");

GeoSOA.olap4js.Util.treeifyAxis = function (cellSetAxis) {
	
	var positions;
	var maxRank;
	var i;

	var prevMembers = [];
    var curNodes = [];
	var treeNode;
	
	var walk = function (parentNode, curPosIdx, curRankIdx) {
		var newMember, curNode;
		
		// do we have a different member than the previous pos at this rank?
		if (positions[curPosIdx].members[curRankIdx] !== prevMembers[curRankIdx]) {
			// we have a new member at this rank
			newMember = positions[curPosIdx].members[curRankIdx];
			prevMembers[curRankIdx] = newMember;
			// add it to the tree
			curNode = {
					member: newMember,
					children: []
			};
			parentNode.children.push(curNode);
			curNodes[curRankIdx] = curNode;
		}
		else {
			// same member as previous pos at this rank; don't add it to
			// the tree
			curNode = curNodes[curRankIdx];
		}
		
		// are we at the end of the position?
		if (curRankIdx < (maxRank - 1)) {
			// no, recurse to the next rank
			walk(curNode, curPosIdx, curRankIdx + 1);
		}

		// we're done, return
	};
	
	positions = cellSetAxis.positions;
	maxRank = cellSetAxis.getAxisMeta().getHierarchyCount();
	
	// initialize the the previous members to null
	for (i = 0; i < maxRank; i++) {
		prevMembers[i] = null;
	}
	
	// initial tree node:
	treeNode = {
		member: null,
		children: []
	};
	
	// iterate over the positions
	for (i = 0; i < cellSetAxis.positions.length; i++) {
		walk(treeNode, i, 0);
	}
	
	return treeNode;
};
